package com.shuziren.webscoket;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
@Component
public class SystemHandshakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 从请求中提取用户身份（如Token、Header等）
        String userId = extractUserId(request,  "username");// 需实现具体提取逻辑
        String token = extractUserId(request, "token");
//        if (userId == null) {
//            return false; // 拒绝连接返回200
//        }
//        if (token == null){
//            return false;//拒绝连接返回200
//        }
//
        attributes.put("userId", userId); // 存入WebSocketSession属性
        attributes.put("token", token);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // 可选：握手后处理
    }

    // 从URL参数中提取userId，支持前端通过 ws://localhost:8080/ws?userId=xxx 方式传递
    private String extractUserId(ServerHttpRequest request,String text) {
        // 判断当前请求是否为Servlet类型（Spring Boot内嵌Tomcat等容器时成立）
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            // 通过getParameter获取URL中的userId参数
            return servletRequest.getParameter(text);
        }
        // 如果不是Servlet类型请求，返回null，表示无法获取userId
        return null;
    }
}
